package cn.com.wxd.amumu.configcenter;

import javax.annotation.PostConstruct;

import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import cn.com.wxd.common.system.SystemInfoUtil;
import cn.com.wxd.service.zookeeper.ZkData;
import cn.com.wxd.service.zookeeper.ZookeeperHelper;
import cn.com.wxd.service.zookeeper.registry.ZookeeperRegistService;

/**
 * Title:
 * Description:
 * <p>
 * Company: Amumu系统
 * Copyright: Copyright (c) 2017
 * All right reserved.
 * Created by WangXuDong on 2017/8/23.
 *
 * @author WangXuDong
 * @version 1.0
 */
@Component
public class ZkManage {
    private static final Logger log = LoggerFactory.getLogger(ZkManage.class);

    @Value("${server.port}")
    private int port;

    @Value("${server.address}")
    private String address;

    @Value("${proj.name}")
    private String serverName;

    @Value("${proj.version}")
    private String version;

    @PostConstruct
    public void registService() {
        if (address == null || address.isEmpty()) {
            address = SystemInfoUtil.getHostAddress();
        }
        if (port == 0) {
            port = 8080;
        }
        ZkData zkData = new ZkData();
        zkData.setIp(address);
        zkData.setVersion(version);
        zkData.setPort(port);
        zkData.setData("");
        log.info("服务开始注册：'" + serverName + "'>>>" + zkData.toString());
        try {
            ZooKeeper zooKeeper = ZookeeperHelper.getInstance().getZooKeeper();//获取默认的zookeeper集群
            ZookeeperRegistService.register(zooKeeper, serverName, zkData); //注册该服务
            log.info("服务注册成功!");
        } catch (Exception e) {
            log.error("服务注册失败" + zkData.toString(),e);
        }
    }
}
